点击上方 "程序员小乐"关注, 星标或置顶一起成长
每天凌晨00点00分, 第一时间与你相约
每日英文
Sometimes, it is better to be alone. That way, nobody can hurt you.
有时候,孤身一人反而更好。那样,就没有人能伤害你了。
每日掏心话
人生匆匆,若不时而驻足欣赏,将会错过它的美好。感情里,最缺的不是激情,而是激情过后的那份坚持。
来自:会炼钢的小白龙 | 责编:乐乐
链接:cnblogs.com/baixianlong/p/10661591.html
程序员小乐(ID:study_tech)第 790 次推文 图片来自百度
往日回顾:又一个程序员“删库跑路”被抓了,一己之力蒸发公司市值超10亿,300万商铺遭瘫痪
正文
2、异步请求的实现
@RequestMapping(value = "/email/servletReq", method = GET) public void servletReq (HttpServletRequest request, HttpServletResponse response) { AsyncContext asyncContext = request.startAsync(); //设置监听器:可设置其开始、完成、异常、超时等事件的回调处理 asyncContext.addListener(new AsyncListener() { @Override public void onTimeout(AsyncEvent event) throws IOException { System.out.println("超时了..."); //做一些超时后的相关操作... } @Override public void onStartAsync(AsyncEvent event) throws IOException { System.out.println("线程开始"); } @Override public void onError(AsyncEvent event) throws IOException { System.out.println("发生错误:"+event.getThrowable()); } @Override public void onComplete(AsyncEvent event) throws IOException { System.out.println("执行完成"); //这里可以做一些清理资源的操作... } }); //设置超时时间 asyncContext.setTimeout(20000); asyncContext.start(new Runnable() { @Override public void run() { try { Thread.sleep(10000); System.out.println("内部线程:" + Thread.currentThread().getName()); asyncContext.getResponse().setCharacterEncoding("utf-8"); asyncContext.getResponse().setContentType("text/html;charset=UTF-8"); asyncContext.getResponse().getWriter().println("这是异步的请求返回"); } catch (Exception e) { System.out.println("异常:"+e); } //异步请求完成通知 //此时整个请求才完成 asyncContext.complete(); } }); //此时之类 request的线程连接已经释放了 System.out.println("主线程:" + Thread.currentThread().getName()); }
@RequestMapping(value = "/email/callableReq", method = GET) @ResponseBody public Callable<String> callableReq () { System.out.println("外部线程:" + Thread.currentThread().getName()); return new Callable<String>() { @Override public String call() throws Exception { Thread.sleep(10000); System.out.println("内部线程:" + Thread.currentThread().getName()); return "callable!"; } }; } @Configuration public class RequestAsyncPoolConfig extends WebMvcConfigurerAdapter { @Resource private ThreadPoolTaskExecutor myThreadPoolTaskExecutor; @Override public void configureAsyncSupport(final AsyncSupportConfigurer configurer) { //处理 callable超时 configurer.setDefaultTimeout(60*1000); configurer.setTaskExecutor(myThreadPoolTaskExecutor); configurer.registerCallableInterceptors(timeoutCallableProcessingInterceptor()); } @Bean public TimeoutCallableProcessingInterceptor timeoutCallableProcessingInterceptor() { return new TimeoutCallableProcessingInterceptor(); }}
@RequestMapping(value = "/email/webAsyncReq", method = GET) @ResponseBody public WebAsyncTask<String> webAsyncReq () { System.out.println("外部线程:" + Thread.currentThread().getName()); Callable<String> result = () -> { System.out.println("内部线程开始:" + Thread.currentThread().getName()); try { TimeUnit.SECONDS.sleep(4); } catch (Exception e) { // TODO: handle exception } logger.info("副线程返回"); System.out.println("内部线程返回:" + Thread.currentThread().getName()); return "success"; }; WebAsyncTask<String> wat = new WebAsyncTask<String>(3000L, result); wat.onTimeout(new Callable<String>() { @Override public String call() throws Exception { // TODO Auto-generated method stub return "超时"; } }); return wat; }
@RequestMapping(value = "/email/deferredResultReq", method = GET) @ResponseBody public DeferredResult<String> deferredResultReq () { System.out.println("外部线程:" + Thread.currentThread().getName()); //设置超时时间 DeferredResult<String> result = new DeferredResult<String>(60*1000L); //处理超时事件 采用委托机制 result.onTimeout(new Runnable() { @Override public void run() { System.out.println("DeferredResult超时"); result.setResult("超时了!"); } }); result.onCompletion(new Runnable() { @Override public void run() { //完成后 System.out.println("调用完成"); } }); myThreadPoolTaskExecutor.execute(new Runnable() { @Override public void run() { //处理业务逻辑 System.out.println("内部线程:" + Thread.currentThread().getName()); //返回结果 result.setResult("DeferredResult!!"); } }); return result; }
二、Spring Boot中异步调用的使用
1、介绍
@Controller@RequestMapping("/app")public class EmailController { //获取ApplicationContext对象方式有多种,这种最简单,其它的大家自行了解一下 @Autowired private ApplicationContext applicationContext; @RequestMapping(value = "/email/asyncCall", method = GET) @ResponseBody public Map<String, Object> asyncCall () { Map<String, Object> resMap = new HashMap<String, Object>(); try{ //这样调用同类下的异步方法是不起作用的 //this.testAsyncTask(); //通过上下文获取自己的代理对象调用异步方法 EmailController emailController = (EmailController)applicationContext.getBean(EmailController.class); emailController.testAsyncTask(); resMap.put("code",200); }catch (Exception e) { resMap.put("code",400); logger.error("error!",e); } return resMap; } //注意一定是public,且是非static方法 @Async public void testAsyncTask() throws InterruptedException { Thread.sleep(10000); System.out.println("异步任务执行完成!"); }}
@Service@Transactional(value = "transactionManager", readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Throwable.class)public class EmailService { @Autowired private ApplicationContext applicationContext; @Async public void testSyncTask() throws InterruptedException { Thread.sleep(10000); System.out.println("异步任务执行完成!"); } public void asyncCallTwo() throws InterruptedException { //this.testSyncTask();// EmailService emailService = (EmailService)applicationContext.getBean(EmailService.class);// emailService.testSyncTask(); boolean isAop = AopUtils.isAopProxy(EmailController.class);//是否是代理对象; boolean isCglib = AopUtils.isCglibProxy(EmailController.class); //是否是CGLIB方式的代理对象; boolean isJdk = AopUtils.isJdkDynamicProxy(EmailController.class); //是否是JDK动态代理方式的代理对象; //以下才是重点!!! EmailService emailService = (EmailService)applicationContext.getBean(EmailService.class); EmailService proxy = (EmailService) AopContext.currentProxy(); System.out.println(emailService == proxy ? true : false); proxy.testSyncTask(); System.out.println("end!!!"); }}
三、异步请求与异步调用的区别
两者的使用场景不同,异步请求用来解决并发请求对服务器造成的压力,从而提高对请求的吞吐量;而异步调用是用来做一些非主线流程且不需要实时计算和响应的任务,比如同步日志到kafka中做日志分析等。
欢迎在留言区留下你的观点,一起讨论提高。如果今天的文章让你有新的启发,学习能力的提升上有新的认识,欢迎转发分享给更多人。
欢迎各位读者加入订阅号程序员小乐技术群,在后台回复“加群”或者“学习”即可。
猜你还想看
阿里、腾讯、百度、华为、京东最新面试题汇集
微服务的生离死别,看这篇就对了!
Java中的对象都是在堆上分配的吗?
IntelliJ IDEA 最常用配置详细图解,适合刚刚用的新人!
文章有问题?点此查看未经处理的缓存